import { readFileSync, writeFileSync } from 'fs'
import { basePath } from './config'
import { PlayList } from './type'

/** 字符串是否字母和数字开头 */
const isStartWithNumberOrLetter = (str: string) => /^\w/.test(str)

/**
 * 列表按中文排序
 * @param {array} list
 * @param {string} prop
 */
export function localeSort<T extends string | object>(
  list: T[],
  prop = ''
): T[] {
  const getCompareVal = (item: string | object) =>
    (prop ? (item as Record<string, string>)[prop] : item) as string

  list.sort((_a, _b) => {
    const a = getCompareVal(_a)
    const b = getCompareVal(_b)

    if (isStartWithNumberOrLetter(a) || isStartWithNumberOrLetter(b)) {
      if (a > b) {
        return 1
      } else if (a < b) {
        return -1
      } else {
        return 0
      }
    } else {
      return a.localeCompare(b)
    }
  })

  return list
}

/** 获取列表路径 */
export function getPlaylistPath(playlist: string) {
  return `${basePath}/playlists/${playlist}.lpl`
}

/**
 * 读取JSON数据
 * @param {string} path
 */
export async function readJSON(path: string) {
  const raw = await readFileSync(path)
  return JSON.parse(raw.toString('utf-8')) as object | []
}

/**
 * 写入JSON数据
 * @param {string} path
 * @param {object|array} data
 */
export async function writeJSON(path: string, data: object | []) {
  return writeFileSync(path, JSON.stringify(data))
}

/**
 * 读取列表数据
 * @param {string} playlist
 */
export function readPlaylist(playlist: string) {
  return readJSON(getPlaylistPath(playlist)) as Promise<PlayList>
}

/**
 * 写入列表数据
 * @param {string} playlist
 * @param {object|array} data
 */
export async function writePlaylist(playlist: string, data: PlayList) {
  const list = normalizePlaylist(data)
  return writeJSON(getPlaylistPath(playlist), list)
}

/** 标准化列表 */
export function normalizePlaylist(data: PlayList) {
  const { default_core_path, default_core_name, items } = data

  // 使用相对地址
  items.forEach(item => {
    item.path = relativePath(item.path)
    item.core_path = relativePath(item.core_path)
  })

  return new PlayList({
    default_core_path: relativePath(default_core_path),
    default_core_name,
    /** 列表中文排序 */
    items: localeSort(items, 'label')
  })
}

/**
 * 转换绝对地址为相对
 */
export function relativePath(path: string) {
  return path.replace(basePath.replace(/\//g, '\\'), '.')
}
